package com.example.models.managers;

import com.example.models.DatabaseInfo;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.PreparedStatement;

import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: dlernatovich
 * Date: 7/12/12
 * Time: 4:40 PM
 * To change this template use File | Settings | File Templates.
 */
public class Register implements DatabaseInfo {

    private String username = "";
    private String password = "";
    private String retypePassword = "";
    private String email = "";
    private Connection connection;
    PreparedStatement ps;

    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_PATTERN =
            "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public Register() {
    }

    public void createNewUser() throws ClassNotFoundException, SQLException {

        Class.forName(DRIVER_NAME);
        connection = (Connection) DriverManager.getConnection(URL_SERVER, USERNAME, PASSWORD);
        ps = (PreparedStatement) connection.prepareStatement("INSERT INTO `users`(`user_name`, `user_password`, `user_email`)" +
                " VALUES (?,?,?)");
        ps.setString(1, this.username);
        ps.setString(2, this.password);
        ps.setString(3, this.email);
        ps.executeUpdate();

        closeConnection();

    }

    public boolean checkPasswordAndMail() {
        if (this.password.equals(this.retypePassword) && checkEmail()) {
            return true;
        }
        return false;
    }

    private boolean checkEmail() {
        boolean result = false;
        if (this.email.equalsIgnoreCase("")) {
            return false;
        }
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(this.email);
        result = matcher.matches();
        return result;
    }

    public void closeConnection() throws SQLException {
        connection.close();
        ps.close();
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setRetypePassword(String retypePassword) {
        this.retypePassword = retypePassword;
    }
}
